package com.hh.message.service;

import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hh.baseframework.util.Convert;
import com.hh.baseframework.util.dto.PageRange;
import com.hh.hibernate.util.dto.HQLParamList;
import com.hh.hibernate.util.dto.PagingData;
import com.hh.message.bean.SysShouEmail;
import com.hh.system.service.impl.BaseService;
import com.hh.usersystem.bean.usersystem.HhXtYh;
import com.hh.usersystem.service.impl.LoginUserUtilService;
import com.hh.usersystem.service.impl.UserService;

@Service
public class SysShouEmailService extends BaseService<SysShouEmail> {
	@Autowired
	private LoginUserUtilService loginUserUtilService;

	@Autowired
	private UserService userService;

	@Override
	public PagingData<SysShouEmail> queryPagingData(SysShouEmail entity,
			PageRange pageRange) {
		return dao.queryPagingData(
				this.getGenericType(0),
				new HQLParamList().addCondition(
						Restrictions.eq("shouUser",
								loginUserUtilService.findLoginUserId()))
						.addCondition(Order.desc("dcreate")), pageRange);
	}

	@Override
	@Transactional
	public SysShouEmail findObjectById(String id) {
		SysShouEmail shouEmail = super.findObjectById(id);
		String[] users = (shouEmail.getUsers() + "," + shouEmail.getSendUser())
				.split(",");

		List<HhXtYh> hhXtYhList = userService.queryListByIds(users);
		Map<String, HhXtYh> hhxtyhMap = Convert.listToMap(hhXtYhList);
		shouEmail.setSendUserName(hhxtyhMap.get(shouEmail.getSendUser())
				.getText());
		List<String> userList = Convert.strToList(shouEmail.getUsers());
		if (!userList.contains(shouEmail.getSendUser())) {
			hhxtyhMap.remove(shouEmail.getSendUser());
		}
		String userstr = Convert.mapToStr(hhxtyhMap, "getText");
		shouEmail.setUserNames(userstr);

		if (shouEmail.getRead() == 0) {
			dao.updateEntity("update " + SysShouEmail.class.getName()
					+ " set read=1 where id=?", new Object[] { id });
		}

		return shouEmail;
	}
}
